﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Newtonsoft.Json.Linq;

namespace LocalServer.Utils
{
    public class HttpServer
    {
        public static event MMSendMsg sendMsgEvent;

        private int port = 9000;
        private HttpListener httpListener;

        public HttpServer()
        {
            this.httpListener = new HttpListener();
        }
        public HttpServer(int port) : this()
        {
            this.port = port;
        }
        public void Run()
        {
            this.httpListener.Prefixes.Add(string.Format("http://+:{0}/", this.port));
            this.httpListener.Start();
            this.httpListener.BeginGetContext(new AsyncCallback(GetContext), this.httpListener);
            Console.WriteLine("Listen Port:" + port);

            JObject jsonObj = new JObject();
            jsonObj.Add("type", "ServerStarted");

            SendMsg(jsonObj);
        }
        public bool IsListening()
        {
            return httpListener.IsListening;
        }
        private async void GetContext(IAsyncResult ar) // 添加 async 修饰符
        {
            HttpListener httpListener = ar.AsyncState as HttpListener;
            HttpListenerContext context = httpListener.EndGetContext(ar);
            httpListener.BeginGetContext(new AsyncCallback(GetContext), httpListener);

            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;

            string rawData;
            using (StreamReader reader = new StreamReader(request.InputStream))
            {
                rawData = await reader.ReadToEndAsync(); // 使用异步读取
            }

            string MacCard = "";
            try
            {
                // 同步处理（如果MessageDealUtils不是耗时操作）
                JObject jsonObj = JObject.Parse(rawData);
                MacCard = MessageDealUtils.messageDeal(jsonObj);
            }
            catch (Exception ex)
            {
                MacCard = $"Error: {ex.Message}";
                // 记录日志
            }

            // 发送响应
            using (Stream output = response.OutputStream)
            {
                byte[] buffer = Encoding.UTF8.GetBytes(MacCard);
                await output.WriteAsync(buffer, 0, buffer.Length); // 使用异步写入
            }
        }
        /* private  void GetContext(IAsyncResult ar)
         {
             string MacCard="";
             HttpListener httpListener = ar.AsyncState as HttpListener;
             HttpListenerContext context = httpListener.EndGetContext(ar);  //接收到的请求context（一个环境封装体）

             httpListener.BeginGetContext(new AsyncCallback(GetContext), httpListener);  //开始 第二次 异步接收request请求

             HttpListenerRequest request = context.Request;  //接收的request数据
             HttpListenerResponse response = context.Response;  //用来向客户端发送回复

             string rawData;
             using (StreamReader reader = new StreamReader(request.InputStream))
             {
                 rawData = reader.ReadToEnd();
             }
             try
             {
                 Task.Run(() =>
                 {
                     JObject jsonObj = JObject.Parse(rawData);
                  MacCard= MessageDealUtils.messageDeal(jsonObj);
                 });

             }
             catch (Exception ex)
             {

             }

             using (Stream output = response.OutputStream)  //发送回复
             {
                 byte[] buffer = Encoding.UTF8.GetBytes(MacCard);
                output.Write(buffer, 0, buffer.Length);
             }
         }*/

        public void SendMsg(JObject obj)
        {
            if (sendMsgEvent != null)
            {
                sendMsgEvent(obj);
            }
        }
    }
}
